﻿using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Media;
using Avalonia.Styling;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Ke.Bee.Localization.Localizer.Abstractions;
using Microsoft.Extensions.Options;
using Moment.Models;
using Moment.ViewModels.Menu;

namespace Moment.ViewModels;

public partial class MainWindowViewModel : ViewModelBase
{
    public string Greeting { get; } = "Welcome to Avalonia!";

    private ObservableCollection<MenuItem> menuItems;

    /// <summary>
    /// 本地化资源
    /// </summary>
    private readonly ILocalizer _localizer;

    /// <summary>
    /// 工具栏按钮集合
    /// </summary>
    [ObservableProperty] private ObservableCollection<MenuItemViewModel> _toolbarMenus;

    public MainWindowViewModel(IOptions<MenuItem[]> menuItems, ILocalizer iLocalizer)
    {
        _localizer = iLocalizer;
        var menuList = menuItems.Value.Where(x => x.Group == "toolBar").Select(x => new MenuItemViewModel(x.LocaleKey)
        {
            Key = x.Key,
            IsActive = x.IsActive == true,
            Icon = string.IsNullOrWhiteSpace(x.Icon) ? null : StreamGeometry.Parse(x.Icon),
            MenuClickCommand = new RelayCommand<MenuItemViewModel>(model =>
            {
                if (model == null || model.IsActive)
                {
                    return;
                }

                var beforeActive = ToolbarMenus.FirstOrDefault(x => x.IsActive);
                if (beforeActive != null)
                {
                    beforeActive.IsActive = false;
                }

                model.IsActive = true;
            })
            // Text = x.Key,
        });
        ToolbarMenus = new ObservableCollection<MenuItemViewModel>(menuList);
    }

    [RelayCommand]
    public void ChangeTheme()
    {
        if (Application.Current is null)
        {
            return;
        }

        Application.Current.RequestedThemeVariant = Application.Current.RequestedThemeVariant == ThemeVariant.Dark
            ? ThemeVariant.Default
            : ThemeVariant.Dark;
    }
}